#include "ParseData.h"


/* returns size of system in GIGA */
int ParseData::Parse(const char* FileName){
	ifstream myData;
	int index = 1;
	int lun_id, offset;
	map<int,double> lun_sizes;
	int final_size = 0;
	double size = 0;
	double max = 0;
	totalExtents = 0;

	myData.open(FileName);
	char output[100];
	if (myData.is_open()) {
		while (!myData.eof()) {
		   myData >> output;

		   if (index == 4){
				stringstream convert (output);
				convert >> std::hex >> lun_id;
				if (lun_sizes.find(lun_id) == lun_sizes.end()){
					lun_sizes[lun_id] = 0;
				}
		   }
		   else if (index == 5){
			   offset = atoi(output);
			   if (offset > lun_sizes[lun_id]) {
				   lun_sizes[lun_id] = (double)(offset/1024);
				   addExtent(lun_id, offset);
				   if ((offset/1024) > max){
					   max = (offset/1024);
				   }
			   }
		   }
		   if (index == 17){
			   index = 1;
		   }
		   else {
			   index++;
		   }
		}
		myData.close();
	}
	else{
		cout << "ERROR: could not open file\n";
		/* TODO: return NULL? */
	}

	int average;

	double temp;
	map<int, double>::iterator it;
	for (it = lun_sizes.begin(); it != lun_sizes.end(); it++){
		temp = it->second + 7680/1024;
		temp = temp*512;
		temp = temp/1024;
		temp = temp/1024;
		size += temp;
	}

	average = (size/lun_sizes.size());
	final_size = (int)size;
	max = ((((max + 7680/1024)*512)/1024)/1024);

	cout << "max lun size is: " << max << " GB" << endl;
	cout << "average lun size is: " << average << " GB" << endl;
	cout << "total number of extents is: " << totalExtents << endl;
	cout << "total system size is: " << final_size << " GB" << endl;
	return final_size;
}

void ParseData::addExtent(int lun_id, int offset){
	map<int, vector<int>>::iterator it = extents.find(lun_id);
	if (it==extents.end()){
		vector<int> ex = vector<int>();
		ex.push_back(offset);
		extents.insert(pair<int,vector<int>> (lun_id, ex));
		totalExtents++;
	}
	else {
		for (int i = 0; i < it->second.size(); i++){
			if (it->second.at(i) == offset){
				return;
			}
		}
		it->second.push_back(offset);
		totalExtents++;
	}
}